{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "planning_prompt = \"\"\"\n",
    "You are a helpful planning agent that can assist users in planning complex tasks which need multi-step browser interaction.\n",
    "\n",
    "## Objective\n",
    "你的任务是收集信息并了解背景情况，以制定出完成任务的详细计划。Reply in Chinese.\n",
    "\n",
    "## Workflow Tips\n",
    "- You may need to do some information gathering e.g. 'search' to get more context about the task. You may also ask the user clarifying questions to get a better understanding of the task. You may return mermaid diagrams to visually display your understanding.\n",
    "- Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task. Returning mermaid diagrams may be helpful here as well.\n",
    "- Then you might ask the user if they are pleased with this plan, or if they would like to make any changes. Think of this as a brainstorming session where you can discuss the task and plan the best way to accomplish it.\n",
    "- If at any point a mermaid diagram would make your plan clearer to help the user quickly see the structure, you are encouraged to include a Mermaid code block in the response. (Note: if you use colors in your mermaid diagrams, be sure to use high contrast colors so the text is readable.\n",
    "- Finally once it seems like you've reached a good plan, generate a  to-do checklist that outlines the specific steps needed to implement the solution. \n",
    "\n",
    "\"\"\"\n",
    "\n",
    "planning_prompt_zh = \"\"\"\n",
    "你是一个能够协助用户规划复杂任务的计划助手，这些任务需要多步骤的浏览器交互。\n",
    "\n",
    "<task>{task_prompt}</task>\n",
    "根据上述问题，如果使用浏览器交互，在访问网页 `{start_url}` 之后，交互的一般过程是什么？\n",
    "\n",
    "请注意，这可以被视为部分可观测的马尔可夫决策过程。不要对自己的计划过于自信。\n",
    "请首先详细重述任务，然后提供一个详细的计划来解决该任务。\n",
    "\n",
    "\"\"\"\n",
    "\n",
    "\n",
    "planning_prompt_data_zh = \"\"\"\n",
    "You are a helpful planning agent that can assist users in planning complex tasks which need multi-step browser interaction.\n",
    "\n",
    "## Objective\n",
    "你的任务是收集信息并了解背景情况，以制定出完成任务的详细计划。Reply in Chinese.\n",
    "\n",
    "## Task\n",
    "<task>{task_prompt}</task>\n",
    "\n",
    "## Workflow Tips\n",
    "- You may need to do some information gathering e.g. 'search' to get more context about the task. You may also ask the user clarifying questions to get a better understanding of the task. You may return mermaid diagrams to visually display your understanding.\n",
    "- Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task. Returning mermaid diagrams may be helpful here as well.\n",
    "- Then you might ask the user if they are pleased with this plan, or if they would like to make any changes. Think of this as a brainstorming session where you can discuss the task and plan the best way to accomplish it.\n",
    "- If at any point a mermaid diagram would make your plan clearer to help the user quickly see the structure, you are encouraged to include a Mermaid code block in the response. (Note: if you use colors in your mermaid diagrams, be sure to use high contrast colors so the text is readable.\n",
    "- Finally once it seems like you've reached a good plan, generate a  to-do checklist that outlines the specific steps needed to implement the solution. \n",
    "\n",
    "### pandas的数据描述如下\n",
    "{data_prompt}\n",
    "\n",
    "\"\"\"\n",
    "\n",
    "data_prompt = \"\"\"\n",
    "{\n",
    "    \"file_path\": \"DataAgent/结果1_全站按日期分组_2023全年.csv\",\n",
    "    \"shape\": [\n",
    "        364,\n",
    "        37\n",
    "    ],\n",
    "    \"dtypes\": {\n",
    "        \"date\": \"object\",\n",
    "        \"order_cnt\": \"float64\",\n",
    "        \"amount\": \"float64\",\n",
    "        \"pay_amount\": \"float64\",\n",
    "        \"discountAmount\": \"float64\",\n",
    "        \"refuelLiters\": \"float64\",\n",
    "        \"path\": \"object\",\n",
    "        \"text_day\": \"object\",\n",
    "        \"code_day\": \"float64\",\n",
    "        \"text_night\": \"object\",\n",
    "        \"code_night\": \"float64\",\n",
    "        \"high\": \"float64\",\n",
    "        \"low\": \"float64\",\n",
    "        \"wc_day\": \"object\",\n",
    "        \"wd_day\": \"object\",\n",
    "        \"wc_night\": \"object\",\n",
    "        \"encoded_wc_night\": \"float64\",\n",
    "        \"wd_night\": \"object\",\n",
    "        \"week\": \"object\",\n",
    "        \"code_week\": \"float64\",\n",
    "        \"holidays\": \"object\",\n",
    "        \"code_holidays\": \"float64\",\n",
    "        \"encoded_holidays\": \"float64\",\n",
    "        \"305_price\": \"float64\",\n",
    "        \"encoded_305_price\": \"float64\",\n",
    "        \"encode_label_305price\": \"object\",\n",
    "        \"encode_weight_305price\": \"float64\",\n",
    "        \"305_order_cnt\": \"float64\",\n",
    "        \"305_amount\": \"float64\",\n",
    "        \"305_discountAmount\": \"float64\",\n",
    "        \"305_refuelLiters\": \"float64\",\n",
    "        \"313_price\": \"float64\",\n",
    "        \"encoded_313_price\": \"float64\",\n",
    "        \"313_order_cnt\": \"float64\",\n",
    "        \"313_amount\": \"float64\",\n",
    "        \"313_discountAmount\": \"float64\",\n",
    "        \"313_refuelLiters\": \"float64\"\n",
    "    }\n",
    "}\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--reason--\n",
      "嗯，用户让我分析今天业绩增长的原因。他们希望我像一个数据分析助手，使用pandas中的数据来找出原因。首先，我需要理解用户的需求，他们可能是一个企业主或者数据分析师，想要了解业绩增长背后的因素，以便未来做出更好的决策。\n",
      "\n",
      "用户的问题看起来比较直接，但作为数据分析师，我不能急于下结论，必须系统地分析。首先，我应该明确分析的目标，也就是找出业绩增长的具体原因。接下来，我需要回顾数据，确保数据的准确性和完整性，因为数据质量直接影响分析结果。\n",
      "\n",
      "然后，我应该计算关键指标，比如总收入、增长率和转化率。这些指标可以帮助我快速了解整体情况。接下来，按维度分组分析，比如按时间、产品、地区、渠道和客户群体来查看数据，这样可以发现哪些因素对增长贡献最大。\n",
      "\n",
      "绘制图表也是很重要的，可视化能更直观地展示数据变化，比如趋势图、柱状图和饼图等。接着，识别异常值和趋势，看看是否有异常情况影响了结果，比如某个时间段或产品的异常增长。\n",
      "\n",
      "然后，进行对比分析，比较增长因素与其他因素的关系，比如高增长产品与低增长产品的差异，或者不同渠道的表现对比。深入分析可能需要查看用户行为数据，比如转化率和跳出率，或者检查是否有促销活动的影响。\n",
      "\n",
      "最后，综合所有分析结果，找出主要原因，并提出建议。整个过程需要系统性和逻辑性，避免主观臆断。现在，我需要把这些步骤整理成一个详细的分析计划，并生成一个检查清单，帮助用户一步步完成分析。\n",
      "\n",
      "--response--\n",
      "### 分析任务重述\n",
      "\n",
      "**任务目标：**  \n",
      "分析今天业绩增长的原因，从数据中找出关键驱动因素。\n",
      "\n",
      "**分析范围：**  \n",
      "使用保存在 pandas 中的历史销售数据，结合时间序列、产品、地区、渠道等维度，系统性地分析业绩增长的可能原因。\n",
      "\n",
      "**分析原则：**  \n",
      "- **系统性：** 从整体到局部，逐步深入分析。  \n",
      "- **数据驱动：** 依赖数据而非主观假设。  \n",
      "- **可验证性：** 确保每一步分析都有数据支持。  \n",
      "\n",
      "---\n",
      "\n",
      "### 分析计划\n",
      "\n",
      "#### 1. 数据准备与初步分析\n",
      "- **数据清洗：** 确保数据完整性和准确性（检查缺失值、异常值）。  \n",
      "- **关键指标计算：** 计算今日业绩（收入、订单量、转化率等）及其环比/同比增长率。  \n",
      "- **时间序列分析：** 绘制近期业绩趋势图，确认今日增长是否符合季节性或周期性规律。  \n",
      "\n",
      "#### 2. 按维度分组分析\n",
      "- **按时间维度：** 分析今日各时段的销售分布，确认增长是否集中在特定时间段。  \n",
      "- **按产品维度：** 分析各产品的销售额、销量及其增长率，确认是否由某类产品的热销驱动。  \n",
      "- **按地区维度：** 分析各地区的销售额分布，确认增长是否集中在特定区域。  \n",
      "- **按渠道维度：** 分析线上/线下渠道的销售表现，确认增长是否由某类渠道驱动。  \n",
      "- **按客户维度：** 分析新老客户的贡献，确认增长是否由新客户获取或老客户复购驱动。  \n",
      "\n",
      "#### 3. 数据可视化\n",
      "- **绘制趋势图：** 展示业绩随时间的变化趋势。  \n",
      "- **绘制柱状图/饼图：** 展示各维度的销售分布。  \n",
      "- **绘制散点图：** 探索变量之间的相关性（如广告投放与销售额的关系）。  \n",
      "\n",
      "#### 4. 异常值与趋势识别\n",
      "- **识别异常值：** 检查数据中是否存在异常波动（如某产品的销售额突然激增）。  \n",
      "- **趋势分析：** 确认增长是否符合长期趋势，或是否为短期波动。  \n",
      "\n",
      "#### 5. 对比分析\n",
      "- **与历史数据对比：** 比较今日数据与历史数据，确认增长是否为常规现象。  \n",
      "- **与同类业务对比：** 如果有多个业务线，比较各业务线的增长情况。  \n",
      "\n",
      "#### 6. 深入分析\n",
      "- **用户行为分析：** 如果有用户行为数据，分析转化率、跳出率等指标的变化。  \n",
      "- **外部因素分析：** 考虑外部因素（如节日、促销活动、天气等）对业绩的影响。  \n",
      "\n",
      "#### 7. 结论与建议\n",
      "- **总结驱动因素：** 确定业绩增长的主要原因（如某产品热销、某渠道表现突出等）。  \n",
      "- **提出建议：** 根据分析结果，提出优化建议（如加大某产品的推广力度）。  \n",
      "\n",
      "---\n",
      "\n",
      "### 分析流程检查清单\n",
      "\n",
      "```markdown\n",
      "# 数据分析流程检查清单\n",
      "\n",
      "## 1. 数据准备与初步分析\n",
      "- [ ] 确保数据完整性和准确性（检查缺失值、异常值）。  \n",
      "- [ ] 计算今日业绩（收入、订单量、转化率等）及其环比/同比增长率。  \n",
      "- [ ] 绘制近期业绩趋势图，确认今日增长是否符合季节性或周期性规律。  \n",
      "\n",
      "## 2. 按维度分组分析\n",
      "- [ ] 按时间维度分析：绘制各时段的销售分布图。  \n",
      "- [ ] 按产品维度分析：计算各产品的销售额、销量及其增长率。  \n",
      "- [ ] 按地区维度分析：绘制各地区的销售额分布图。  \n",
      "- [ ] 按渠道维度分析：比较线上/线下渠道的销售表现。  \n",
      "- [ ] 按客户维度分析：分析新老客户的贡献比例。  \n",
      "\n",
      "## 3. 数据可视化\n",
      "- [ ] 绘制趋势图（如折线图）展示业绩随时间的变化。  \n",
      "- [ ] 绘制柱状图/饼图展示各维度的销售分布。  \n",
      "- [ ] 绘制散点图探索变量之间的相关性（如广告投放与销售额）。  \n",
      "\n",
      "## 4. 异常值与趋势识别\n",
      "- [ ] 识别数据中的异常值（如某产品的销售额突然激增）。  \n",
      "- [ ] 确认增长是否符合长期趋势，或是否为短期波动。  \n",
      "\n",
      "## 5. 对比分析\n",
      "- [ ] 与历史数据对比，确认增长是否为常规现象。  \n",
      "- [ ] 与同类业务对比，比较各业务线的增长情况。  \n",
      "\n",
      "## 6. 深入分析\n",
      "- [ ] 如果有用户行为数据，分析转化率、跳出率等指标的变化。  \n",
      "- [ ] 考虑外部因素（如节日、促销活动、天气等）对业绩的影响。  \n",
      "\n",
      "## 7. 结论与建议\n",
      "- [ ] 总结业绩增长的主要原因（如某产品热销、某渠道表现突出等）。  \n",
      "- [ ] 根据分析结果，提出优化建议（如加大某产品的推广力度）。  \n",
      "```\n",
      "\n",
      "---\n",
      "\n",
      "### 示例代码（Python）\n",
      "\n",
      "以下是一个简单的代码示例，帮助你快速上手：\n",
      "\n",
      "```python\n",
      "import pandas as pd\n",
      "import matplotlib.pyplot as plt\n",
      "import seaborn as sns\n",
      "\n",
      "# 1. 读取数据\n",
      "df = pd.read_csv('sales_data.csv')\n",
      "\n",
      "# 2. 计算今日业绩\n",
      "today_data = df[df['date'] == 'today']\n",
      "total_revenue = today_data['revenue'].sum()\n",
      "growth_rate = (total_revenue - df[df['date'] == 'yesterday']['revenue'].sum()) / df[df['date'] == 'yesterday']['revenue'].sum() * 100\n",
      "\n",
      "# 3. 绘制趋势图\n",
      "plt.figure(figsize=(10, 6))\n",
      "sns.lineplot(x='date', y='revenue', data=df)\n",
      "plt.title('Revenue Trend Over Time')\n",
      "plt.show()\n",
      "\n",
      "# 4. 按产品维度分析\n",
      "product_revenue = today_data.groupby('product')['revenue'].sum().reset_index()\n",
      "plt.figure(figsize=(10, 6))\n",
      "sns.barplot(x='product', y='revenue', data=product_revenue)\n",
      "plt.title('Revenue by Product')\n",
      "plt.show()\n",
      "\n",
      "# 5. 按渠道维度分析\n",
      "channel_revenue = today_data.groupby('channel')['revenue'].sum().reset_index()\n",
      "plt.figure(figsize=(10, 6))\n",
      "sns.pieplot(x='revenue', labels='channel', data=channel_revenue)\n",
      "plt.title('Revenue by Channel')\n",
      "plt.show()\n",
      "```\n",
      "\n",
      "---\n",
      "\n",
      "通过以上流程和代码示例，你可以系统性地分析业绩增长的原因，并确保分析结果具有数据支持和逻辑性。\n"
     ]
    }
   ],
   "source": [
    "from openai import OpenAI\n",
    "\n",
    "client = OpenAI(\n",
    "    api_key=\"sk-0e687ddcf0164a6fb66c1096447223c4\",  # 阿里百炼大模型API获取：https://bailian.console.aliyun.com/?apiKey=1#/api-key\n",
    "    base_url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\" # 使用文档：https://help.aliyun.com/zh/model-studio/getting-started/what-is-model-studio\n",
    ")\n",
    "\n",
    "def llm(system_prompt, task_prompt, data_prompt):\n",
    "    query = planning_prompt_data_zh.format(task_prompt=task_prompt, data_prompt=data_prompt)\n",
    "    completion = client.chat.completions.create(\n",
    "        model=\"deepseek-r1-distill-qwen-32b\", # deepseek-r1, deepseek-r1-distill-qwen-32b\n",
    "        messages=[{'role': 'system', 'content': system_prompt},\n",
    "                  {'role': 'user', 'content': query}],\n",
    "        )\n",
    "    return completion.choices[0].message.content, completion.choices[0].message.reasoning_content\n",
    "\n",
    "\n",
    "response, reason = llm(\"\", \"帮我分析下今天业绩增长的原因\", data_prompt)\n",
    "print(\"--reason--\")\n",
    "print(reason)\n",
    "print(\"\\n--response--\")\n",
    "print(response)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
